// pages/attractionsPaid/attractionsPaid.js
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    spotId:"",
    ticketId:"",
    bookingtime:"",
    attraction: {},
    outTradeNo:"",
    num: 1, 
    price: 0 
  },
  onClickLeft(){
    wx.navigateBack();
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    const Id = options.Id;
    const totalnum = options.num;
    const totalprice = options.price / 100;
    const ticketId = options.ticketId;
    const selectedDate = options.selectedDate;
    // console.log(totalnum)
    // console.log(totalprice)
    this.setData({
      spotId:Id,
      num:totalnum,
      price:totalprice,
      ticketId:ticketId,
      bookingtime:selectedDate
    })
    this.loadAttractions(Id),
    this.generatePaymentQRCode(this.data.attraction.name,totalprice)
  },
  loadAttractions(Id){
      wx.request({
        url: `http://localhost:8080/system/spot/${Id}`,
        header: {
          Authorization: app.globalData.token
        },
        success: (res) => {
          if (res.data.code === 200 && res.data.data) {
            const spot = res.data.data;
            const baseUrl = 'http://localhost:8080';
        
            // 构造 attraction 对象
            const attraction = {
              imageUrl: baseUrl + spot.imgUrl,       // 拼接图片路径
              name: spot.name,                       // 景点名称
              rating: spot.star,                     // 评分
              reviewCount: spot.commentCount || 0,    // 评论数量
            };
        
            // 更新页面数据
            this.setData({
              attraction: attraction,
            });
           
          } else {
            wx.showToast({ title: '加载景点失败', icon: 'none' });
          }
        }
      })
  },
  // 调用后端生成二维码接口
  generatePaymentQRCode(name, amount) {
    const app = getApp();
    const outTradeNo = `ORDER_${Date.now()}`;

    wx.request({
      url: 'http://localhost:8080/alipay/pay',
      header: {
        Authorization: app.globalData.token
      },
      data: {
        subject: name,
        outTradeNo: outTradeNo,
        totalAmount: amount
      },
      responseType: 'arraybuffer',
      success: (res) => {
        if (res.statusCode === 200) {
          const base64 = wx.arrayBufferToBase64(res.data);
          this.setData({
            qrCodeUrl: 'data:image/jpeg;base64,' + base64.trim(),
            outTradeNo: outTradeNo // 保存订单号
          });

          this.startPolling(outTradeNo); // 启动轮询

          console.log(outTradeNo)
        } else {
          wx.showToast({ title: '获取二维码失败', icon: 'none' });
        }
      },
      fail: () => {
        wx.showToast({ title: '网络请求失败', icon: 'none' });
      }
    });
  },
  startPolling(outTradeNo) {
    const interval = setInterval(() => {
      wx.request({
        url: 'http://localhost:8080/alipay/queryPay',
        header: {
          Authorization: app.globalData.token
        },
        data: {
          outTradeNo: outTradeNo
        },
        success: (res) => {
          if (res.data === 'TRADE_SUCCESS') {
            clearInterval(interval); // 停止轮询

            // 调用新增订单接口
          this.createOrder(outTradeNo);

            wx.showToast({
              title: '支付成功',
              icon: 'success',
            });

          setTimeout(function(){
            wx.switchTab({
              url: '/pages/order/order',
            })
          },2000);


          }
        },
        fail: () => {
          clearInterval(interval); // 停止轮询
          console.log('查询支付状态失败');
        }
      });
    }, 3000); // 每3秒查询一次
  },
  getCurrentTime() {
    const now = new Date();
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0');
    const day = String(now.getDate()).padStart(2, '0');
    const hours = String(now.getHours()).padStart(2, '0');
    const minutes = String(now.getMinutes()).padStart(2, '0');
    const seconds = String(now.getSeconds()).padStart(2, '0');
  
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  },
  createOrder(orderNo) {
    const app = getApp();
    // 构造订单数据
    const orderData = {
      tid: this.data.ticketId,
      aid: this.data.spotId,
      uid: app.globalData.userInfo.userId,   
      ticketNum: this.data.num,
      price: this.data.price,
      orderNumber: orderNo,
      state: 1,
      bookingtime: this.data.bookingtime,
      donetime: this.getCurrentTime()
    };
  
    console.log(orderData.donetime)
    wx.request({
      url: 'http://localhost:8080/system/infos',
      method: 'POST',
      header: {
        Authorization: app.globalData.token,
        'content-type': 'application/json'
      },
      data: orderData,
      success: (res) => {
        if (res.statusCode === 200 && res.data.code === 200) {
          console.log('订单创建成功', res.data);
        } else {
          console.error('订单创建失败', res.data.msg || '未知错误');
        }
      },
      fail: (err) => {
        console.error('请求失败', err);
      }
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})